package com.example.ytyproject.controller;


import com.alibaba.fastjson.JSONObject;
import com.example.ytyproject.component.ElasticsearchService;
import com.example.ytyproject.entity.Logs;
import com.example.ytyproject.service.ILogsService;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yg
 * @since 2023-10-30
 */
@Api(tags = "日志管理API")
@RestController
@RequestMapping("/logs")
public class LogsController {

    @Autowired
    private ILogsService logsService;
    @Autowired
    private ElasticsearchService elasticsearchService;

    @Autowired
    private ObjectMapper objectMapper;

    @PostMapping("insert")
    @ApiOperation(value = "批量插入日志信息",notes = "批量插入日志信息")
    public void insert() {
        Logs logs = new Logs();
        for (int i = 0; i < 1000; i++) {
            logs = new Logs();
            logs.setTitle("好的"+i)
                    .setContent(System.currentTimeMillis()+"贵阳")
                    .setCreateTime(LocalDateTime.now());
            logsService.save(logs);
        }

    }

    @ApiOperation(value = "讲数据批量导入ES",notes = "讲数据导入ES")
    @PostMapping("batchInsertToEs")
    public void batchInsertToEs() {
        elasticsearchService.batchInsertToEs();
    }

    @ApiOperation(value = "新增数据（同时保存到es）",notes = "讲数据导入ES")
    @PostMapping("add")
    public void add(@RequestBody Logs logs) {
        logsService.add(logs);
    }

    @ApiOperation(value = "修改数据",notes = "讲数据导入ES")
    @GetMapping("updateData")
    public void updateData(@RequestParam("id") String id) {
        Logs logs = logsService.getById(id);
        if (logs != null) {
            logs.setTitle("999999");
            logsService.updateById(logs);
            elasticsearchService.updateEsData(logs);
        }
    }

    @GetMapping("queryList")
    public JSONObject queryList() {
        JSONObject jsonObject = logsService.queryList();
        long l = elasticsearchService.queryTotal();
        List<Map<String, Object>> list = elasticsearchService.list();
        jsonObject.put("total", l);
        jsonObject.put("list", list);
        return jsonObject;
    }

}
